#ifndef CLOUD_SHADOW
#define CLOUD_SHADOW

#include "CloudShape.cginc"

// Shadow
sampler2D _shadow_map;
uniform sampler2D _Shadowmap;

float3 hard_shadow(float3 start_pos)
{
    float shadow_bias = 0.04;
    float4 shadow_coord_vp = mul(_shadow_cam_VP, float4(start_pos, 1.0));
    float4 shade_point_to_cam = -mul(_shadow_cam_V, float4(start_pos, 1.0));
    const float shadow_depth = tex2D(_shadow_map, shadow_coord_vp.xy); // 当前位置对应阴影图中位置处的深度
    const float cur_depth = shade_point_to_cam.z / 99999 - shadow_bias;
    float shadow_mask = max(step(cur_depth, shadow_depth), 0.4);
    float shadow_diff = (shade_point_to_cam.z / 99999 - shadow_bias - shadow_depth);
    return float3(shadow_mask, shadow_diff, saturate(pow((cur_depth) * 2, 2.0)));
}

float3 fragPCF4x4(float3 start_pos)
{
    float4 shadow_coord_vp = mul(_shadow_cam_VP, float4(start_pos, 1.0));
    float4 shade_point_to_cam = -mul(_shadow_cam_V, float4(start_pos, 1.0));

    float shadowmask = 0;
    float depth_sum = 0;
    const float cur_depth = shade_point_to_cam.z / 99999 - 0.04;
    for (float y = -1.5; y <= 1.5; y += 1.0)
        for (float x = -1.5; x <= 1.5; x += 1.0)
        {
            const float depth = offset_lookup(_shadow_map, shadow_coord_vp.xy, float2(x, y));
            const float mask = max(step(cur_depth, depth), 0.0);
            shadowmask += mask;
            depth_sum += depth;
        }
    // return float2(shadowmask/16, depth_sum/10);
    return float3(shadowmask / 16, step(cur_depth - depth_sum / 16, -0.05) ? -0.05 : cur_depth - depth_sum / 16, saturate(cur_depth * 2));
}

float3 shadow_march(const float3 ray_origin, const float3 ray_dir, const float2 t_near_far, const float depth, const float k)
{
    float t_near = t_near_far.x;
    float t_far = max(t_near, t_near_far.y);
    float threshold = -1000000;
    float res = 1;
    float it=0;
    while (t_near < t_far-1000) // 直射光不会扰动？
    {
        const float3 pos_near = ray_origin + ray_dir * t_near; // 每一次步进之后距离初始距离t_near
        const float value = distance_field(pos_near, t_near); // 计算得到步进的位置到sdf的距离
        const float result = value; // 到sdf的距离，离得越远noise效果越低
        it+=1;
        if (result >= threshold)
        {
            res = min(res, k * result / t_near);
            t_near += result * 1.6;
            threshold = 0.6 * result;
            // 在抵达渲染位置之前，就已经抵达SDF，阴影内
            // if (result <= 1) return 0;
            if (result <= 1) return float3(0.0, (depth - t_near) / 99999, saturate(depth / 50000));
        }
        else
        {
            // 当某一时刻到sdf的距离不到0.6倍的上一次了距离了
            t_near += (-threshold);
            threshold = -1000000;
        }
    }
    return float3(res, -0.05, saturate(depth / 50000)); // 抵达渲染位置时才接触到SDF，直受光
}

float3 get_light_plane_point(float3 light_dir)
{
    return saturate(sign(light_dir)) * _corner_out;
}

#endif
